package cn.itsource.org.controller;

import cn.itsource.org.domain.Department;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import cn.itsource.util.AjaxResult;
import cn.itsource.util.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/department")
//@CrossOrigin//允许跨域访问
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @GetMapping //@RequestMapping( method = {RequestMethod.GET} )
    public List<Department> getAll(){
        return  departmentService.queryAll();
    }

    //RequestBody 接收请求的json对象
    @PutMapping //@RequestMapping( method = {RequestMethod.PUT} )
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult saveOrUpdate(@RequestBody Department department){
        try {
            if (department.getId()==null){
                departmentService.save(department);
            }else {
                departmentService.update(department);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }
    //前端发送请求  loclhost:8080/department/2
    @DeleteMapping("/{id}")    //@RequestMapping( method = {RequestMethod.DELETE} )
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }


    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return departmentService.queryById(id);
    }

    @PostMapping
    public PageInfo<Department> page( @RequestBody DepartmentQuery query){
        return  departmentService.queryPage(query);
    }
    //前端发送的数据  数组   [10,11,12]
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody Long[] ids){
        try {
            System.out.println(Arrays.toString(ids));
            // 删除所有 id数据
            /*
                方案1：循环数组  -- 循环调用delete方法
                方案2：批量删除
                  delete form t_department where id in(43,44,45)
             */
            departmentService.patchDel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }

    //获取部门树的方法
    @GetMapping("/deptTree")
    public List<Department> getDeptTree(){
        return departmentService.getDeptTree();
    }


}
